const express = require('express')
const app = express()

const cors = require('cors')
app.use(cors())

app.use(express.urlencoded({ extended: false }))

// 在所有路由之前封装res.cc函数
app.use((req, res, next) => {
  res.cc = (err, status = 1) => {
    res.send({
      status,
      // err的值，可能是一个字符串，也可能是一个错误对象
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})

const config = require('./config')
const expressJWT = require('express-jwt')
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api/] }))

const userRouter = require('./router/user')
app.use('/api', userRouter)
const userinfoRouter = require('./router/userinfo')
app.use('/my', userinfoRouter)

app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    return res.cc('身份验证失败')
  }
  res.cc(err)
})

app.listen(8000, () => {
  console.log('api server running at http://127.0.0.1:8000')
})
